#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Comm.hpp"

using namespace std;
void Usage(const std::string &process)
{
    std::cout << "Usage: " << process << " server_ip server_port" << std::endl;
}

int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
    }
    std::string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {   

    }


    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    inet_pton(AF_INET,serverip.c_str(),&server.sin_addr);

    int n = connect(sockfd,CONV(&server),sizeof(server));
    if(n != 0)
    {
        std::cerr << "connect err" << std::endl;
        return 2;
    }
    while(true)
    {
        string instring;
        std::cout << "please enter#";
        getline(cin,instring);
        int n = write(sockfd,instring.c_str(),instring.size());
        if(n > 0)
        {
            char buff[1024];
            int m = read(sockfd,buff,sizeof(buff)-1);
            if(m > 0)
            {
                buff[m] = 0;
                cout <<"get a message:"<< buff <<endl;
            }
            else break;
        }
        else
        {
            break;
        }
    }
    close(sockfd);
    return 0;

}